<template>
  <view class="container" :style="{ height: conHeight }">
    <div class="lcr-container">
      <view class="left-container">
        <view class="ul">
          <view
            class="li"
            :class="{ active: item.id === liId }"
            v-for="(item, i) in recipeClassList"
            :key="item.id"
            @click="handleLiClick(item.id, 1)"
          >
            <view>{{ item.name }}</view>
          </view>
        </view>
      </view>
      <view class="center-container">
        <view class="ul">
          <view
            class="li"
            :class="{ active: item.id === liId2 }"
            v-for="(item, i) in recipeClassList2"
            :key="item.id"
            @click="handleLiClick(item.id, 2)"
          >
            <view>{{ item.name }}</view>
          </view>
        </view>
      </view>
      <view class="right-container">
        <view class="ul">
          <u-radio-group
            v-model="selectValue"
            placement="column"
            @change="checkboxChange"
          >
            <view
              class="li"
              v-for="(item, i) in recipeClassList3"
              :key="item.id"
            >
              <u-radio :label="item.name" :name="item.name"></u-radio>
            </view>
          </u-radio-group>
        </view>
      </view>
    </div>
    <view class="bottom-container">
      <view>
        <view style="font-weight: bold">已选菜品：</view>
        <view>{{ selectValue }}</view>
        <!-- <view>{{ selectValue.join('、') }}</view> -->
        <!-- <view>{{
          [...new Set(allCheckboxValue.concat(selectValue))].join('、')
        }}</view> -->
      </view>
      <u-button
        type="primary"
        :loading="loading"
        loadingText="加载中"
        text="随机选择"
        size="large"
        @click="handleRandomSelect"
      ></u-button>
    </view>
    <u-popup
      v-if="details.length"
      :show="popupShow"
      mode="right"
      round="10"
      zIndex="999"
      @close="close"
      @open="open"
    >
      <view class="popup-content">
        <view class="ul">
          <view
            class="li"
            v-for="item in details"
            :key="item.id"
            @click="handleDetails(item)"
          >
            <view class="name">{{ item.name }}</view>
            <view class="desc">{{ item.desc }}</view>
            <image
              class="cover"
              :src="item.cover"
              mode="aspectFit"
              @click.stop="handlePreviewImage(item.cover)"
            />
            <view class="ingredient"
              >材料：{{
                item.ingredient.map(item => item.name).join('、')
              }}</view
            >
          </view>
        </view>
      </view>
    </u-popup>
    <u-toast ref="uToastRef"></u-toast>
    <u-loading-page :loading="loading"></u-loading-page>
  </view>
</template>

<script setup>
import { onLoad, onShow } from '@dcloudio/uni-app'

const conHeight = ref('')
const app_id = 'jnfmrsexjrieuwtc'
const app_secret = 'MW0xODl1NHI4NkxBUHd2Qkt2SmRQQT09'
const recipeClassList = ref([])
const recipeClassList2 = ref([])
const recipeClassList3 = ref([])

const liId = ref('')
const liId2 = ref('')
const selectValue = ref('')
const allCheckboxValue = ref([])
const popupShow = ref(false)
const loading = ref(false)
const uToastRef = ref(null)
const details = ref([])

// console.clear()
nextTick(() => {
  // 设置容器的高度
  uni.getSystemInfo({
    success: res => {
      conHeight.value = res.windowHeight + 'px'
    }
  })
})

watch(
  () => recipeClassList3.value,
  (nv, ov) => {
    // console.log('监听到 selectValue 发生变化', ov, ' ==> ', nv)
    // 保留所有已选的数据
    // allCheckboxValue.value = [
    //   ...new Set(allCheckboxValue.value.concat(selectValue.value))
    // ]
    // 勾选已选的数据
    selectValue.value = ''
    // selectValue.value = nv
    //   .filter(item => allCheckboxValue.value.includes(item.name))
    //   .map(item => item.name)
  }
)

onLoad(async _ => {
  uni.hideTabBar()
  recipeClassList.value = await getRecipeClassList()
  if (recipeClassList.value.length) liId.value = recipeClassList.value[0].id
  getDataList()
})

function publicInterMethod(url, data) {
  loading.value = true
  // 每次请求都至少一秒
  let startTime = +new Date()
  return new Promise((resolve, reject) => {
    uni.request({
      url,
      data: {
        ...data,
        page: 1,
        limit: 100,
        app_id,
        app_secret
      },
      method: 'GET',
      success({ data }) {
        if (data.code === 1 && data.data) {
          // console.log('success', data.data)
          resolve(data.data)
        } else {
          uToastRef.value.show({
            type: 'error',
            message: data.msg,
            iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
          })
        }
      },
      fail(err) {
        // console.log('error', err)
        resolve([])
        if (err.errMsg.indexOf('request:fail') > -1) {
          uToastRef.value.show({
            type: 'error',
            message: '请求失败，请检查接口是否可用！',
            iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
          })
        }
      },
      complete() {
        let endTime = +new Date()
        let time = 1000 - (endTime - startTime)
        if (time > 0) {
          setTimeout(() => {
            loading.value = false
          }, time)
        } else {
          loading.value = false
        }
      }
    })
  })
}

async function getRecipeClassList(id = -1) {
  return await publicInterMethod(apiModules.home.apiGetRecipeCategories, {
    category_id: id
  })
}

function getDataList() {
  setTimeout(async _ => {
    recipeClassList2.value = await getRecipeClassList(liId.value)
    if (recipeClassList2.value.length)
      liId2.value = recipeClassList2.value[0].id
    setTimeout(async _ => {
      recipeClassList3.value = await getRecipeClassList(liId2.value)
    }, 1000)
  }, 1000)
}

async function getSearchInfo() {
  return await publicInterMethod(apiModules.home.apiSearchRecipeByKeyword, {
    // keyword: [
    //   ...new Set(allCheckboxValue.value.concat(selectValue.value))
    // ].join('、')
    // keyword: selectValue.value.join('、')
    keyword: selectValue.value
    // keyword: '老鸭'
  })
}

async function handleLiClick(id, type) {
  if (type === 1) {
    liId.value = id
    getDataList()
  } else {
    liId2.value = id
    recipeClassList3.value = await getRecipeClassList(liId2.value)
  }
}
function checkboxChange(e) {
  selectValue.value = e
}
async function handleRandomSelect() {
  details.value = (await getSearchInfo()).list
  if (details.value.length) {
    popupShow.value = true
  } else {
    uToastRef.value.show({
      type: 'error',
      message: '未搜索到菜谱！',
      iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
    })
  }
}

function open() {
  popupShow.value = true
}

function close() {
  popupShow.value = false
}

function handleDetails(item) {
  uni.navigateTo({
    url: `/pages/details/index?id=${item.id}&name=${item.name}`
  })
}

function handlePreviewImage(url) {
  uni.previewImage({
    current: 0,
    urls: [url],
    loop: true,
    longPressActions: true
  })
}
</script>

<style lang="scss">
.container {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}
.lcr-container {
  display: flex;
  box-sizing: border-box;
  height: 75%;
  border-bottom: 1px solid #ddd;
}
.left-container,
.center-container,
.right-container {
  width: 30%;
  overflow-y: auto;
}
.left-container,
.center-container {
  border-right: 1px solid #ddd;
  .ul {
  }
  .li {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 88rpx;
    border-bottom: 1px solid #ddd;
    font-size: 28rpx;
    color: #333;
    &.active {
      background-color: #ffd976;
      color: #2979ff;
    }
  }
}
.right-container {
  flex: 1;
  .ul {
    padding: 10px 0;
  }
  .li {
    height: 88rpx;
    padding: 0 10px;
  }
}
.bottom-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-sizing: border-box;
  height: 25%;
  padding: 10px;
  overflow-y: auto;
  .ul {
    padding: 10px 0;
  }
  .li {
    height: 88rpx;
    padding: 0 10px;
  }
}
.popup-content {
  max-width: 70vw;
  height: 100%;
  padding: 20rpx;
  border-radius: 10rpx;
  overflow-y: auto;
  box-sizing: border-box;
  .ul {
    .li {
      padding: 20rpx 0;
      border-bottom: 1rpx solid #ddd;
      .name {
        line-height: 30 * 2rpx;
        text-align: center;
        font-size: 16 * 2rpx;
        font-weight: bold;
      }
      .desc {
        line-height: 22 * 2rpx;
        font-size: 14 * 2rpx;
        color: #333;
      }
      .cover {
        width: 100%;
        margin: 20rpx 0;
      }
    }
  }
}
</style>
